package org.mozhu.learning.algo.linked_list.single;

import org.mozhu.learning.algo.linked_list.List;

public class SLinkedList<E> implements List<E> {

    private SNode head = new SNode();
    private int size = 0;

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size() == 0;
    }

    @Override
    public void add(E obj) {
        SNode l = findLast();
        SNode node = new SNode(obj);
        if (l == null) {
            head.setNext(node);
        } else {
            l.setNext(node);
        }
        size++;
    }

    public SNode findLast() {
        if (head.getNext() == null) {
            return null;
        }
        SNode last = head.getNext();
        while (last.getNext() != null) {
            last = last.getNext();
        }
        return last;
    }

    @Override
    public void add(int index, E obj) {

    }

    @Override
    public void remove(int index) {
        SNode next = head.getNext();

    }

    @Override
    public E get(int index) {
        checkBound(index);
        SNode<E> next = head.getNext();
        for (int i = 0; i < index; i++) {
            next = next.getNext();
        }
        return next.getData();
    }

    private void checkBound(int index) {
        if (index < 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
    }

    @Override
    public String toString() {
        if(isEmpty()){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        SNode next = head.getNext();
        while (next != null) {
            sb.append(next.getData().toString()).append(">");
            next = next.getNext();
        }
        String s = sb.toString();
        return s.substring(0, s.length() - 1);
    }
}
